<template>
  <div class="">
    <div class="backend-header-breadcrumb">
      <a-breadcrumb :style="{ margin: '16px 0' }">
        <a-breadcrumb-item>文章管理</a-breadcrumb-item>
        <a-breadcrumb-item>{{ isEdit ? '编辑' : '创建' }}文章</a-breadcrumb-item>
      </a-breadcrumb>
    </div>

    <div class="backend-body">
      <div class="backend-header-button-group">
        <div class="backend-header-button"></div>
        <div></div>
      </div>

      <div class="backend-table">
        <a-space direction="vertical" size="large" :style="{ width: '100%' }">
          <!-- form 表单 -->
          <!-- 
          :model绑定表单数据 
          ref 绑定表单实例
          rules 验证规则
          -->
          <a-form
            :model="form"
            layout="vertical"
            ref="formRef"
            :rules="rules"
            :loading="formLoading"
          >
            <a-form-item>
              <!-- 保存按钮 -->
              <!-- 
              @click 点击事件 提交数据
              :style 设置按钮样式
              handleSave 通过form ref属性操作form表单
               -->
              <a-button type="primary" @click="handleSave" :style="btnStyle" :loading="btnLoading">
                <template #icon>
                  <icon-save />
                </template>
                保存
              </a-button>
            </a-form-item>

            <a-form-item field="title" label="文章标题">
              <a-input
                v-model="form.title"
                placeholder="请输入文章标题..."
                :disabled="titleDisabled"
              />
            </a-form-item>

            <a-form-item field="summary" label="文章概要">
              <a-input
                v-model="form.summary"
                placeholder="请输入文章概要..."
                :disabled="summaryDisabled"
              />
            </a-form-item>

            <a-form-item field="content" label="文章内容">
              <MdEditor
                v-model="form.content"
                theme="light"
                :showToolbarName="true"
                :disabled="contentDisabled"
              />
            </a-form-item>

            <!-- <a-form-item field="isRead">
              <a-checkbox v-model="form.isRead"> I have read the manual </a-checkbox>
            </a-form-item> -->
          </a-form>
        </a-space>
      </div>
    </div>
  </div>
</template>

<script setup>
import { Notification } from '@arco-design/web-vue'

import { onMounted, ref } from 'vue'
import { MdEditor } from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'
import { UPDATE_BLOG, CREATE_BLOG, DESCRIBE_BLOG } from '@/api/vblog'
import { useRouter } from 'vue-router'
const router = useRouter()

const btnLoading = ref(false)
const formLoading = ref(false)
const formRef = ref(null)
const isEdit = ref(false)
const describeBlog = ref(null)

const titleDisabled = ref(false)
const summaryDisabled = ref(false)
const contentDisabled = ref(false)
// 页面加载时，判断是否有id参数
// 通过url参数判断是否为编辑
onMounted(async () => {
  router.currentRoute.value.query.id ? (isEdit.value = true) : (isEdit.value = false)

  if (isEdit.value) {
    try {
      formLoading.value = true

      describeBlog.value = await DESCRIBE_BLOG(router.currentRoute.value.query.id)
      if (describeBlog.value.status === 200) {
        form.value = describeBlog.value.data
      } else {
        console.log('err')
      }
    } catch (error) {
      // 如果无法获取数据，则禁用表单
      titleDisabled.value = true
      summaryDisabled.value = true
      contentDisabled.value = true
      Notification.error({
        title: error.message
      })
    } finally {
      formLoading.value = false
    }
  }
})

// form字段绑定 ,这里的id 可以在form表达中隐藏，或者从路由中获取，在更新时使用id
const form = ref({
  title: '',
  summary: '',
  content: '# 请输入文章内容',
  tags: {}
})

// 通过form ref属性操作form表单
const handleSave = async () => {
  // 判断ref属性是否为null
  if (!formRef.value) return

  // 调用ref的validate方法,验证表单
  await formRef.value.validate((valid) => {
    // 如果valid有返回值，表单验证不通过
    if (valid) {
      console.log('error submit!')
      return false
    }
    // 如果没有返回值，表单验证通过 (undefined)
    // console.log(valid)

    try {
      btnLoading.value = true
      if (isEdit.value) {
        // 根据id更新内容
        const update_resp = UPDATE_BLOG(router.currentRoute.value.query.id, form.value)
        if (update_resp.code != 200) {
          Notification.error({ title: `更新失败 $(update_resp.message)` })
        } else {
          Notification.success({
            title: '成功',
            message: '更新成功'
          })
        }

        router.push('/backend/blogs')
      } else {
        // 创建文章
        const create_resp = CREATE_BLOG(form.value)
        console.log(create_resp.message)

        if (create_resp.code != 200) {
          Notification.error({ title: `创建失败 $(create_resp.message)` })
        } else {
          Notification.success({
            title: '创建成功'
          })
        }
      }
    } catch (error) {
      Notification.error({
        title: '失败',
        message: '失败'
      })
      console.log(error)
    } finally {
      btnLoading.value = false
    }
  })
}

// 校验规则
const rules = {
  title: [
    {
      required: true,
      message: '请输入文章标题',
      trigger: 'blur'
    }
  ],
  summary: [
    {
      required: true,
      message: '请输入文章概要'
      // trigger: 'blur'
    }
  ],
  content: [
    {
      required: true,
      message: '请输入文章概要'
      // trigger: 'blur'
    }
  ]
}
const btnStyle = {
  width: '100px',
  marginLeft: 'auto'
}
</script>

<style lang="css" scoped>
.backend-header-breadcrumb {
  padding: 8px;
  background: #fff;
  border-bottom: 1px solid #eee;
  display: flex;
  align-items: center;
}

.backend-body {
  padding-left: 5px;
  padding-right: 20px;
}

.backend-table {
  margin-left: 10px;
}
.backend-header-button-group {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.backend-header-button {
  padding: 10px;
}
</style>
